from fastapi import APIRouter, Depends
from sqlmodel import Session, select
from crud.systems import user as user_crud
from common import response_code
import models
from dependencies import engine, SessionDep
from typing import Annotated
from routers.auth import get_current_sys_user
from common import exception

router = APIRouter()

"""查询用户基本信息

Keyword arguments:
id -- 用户id（非必填）
user -- 登录用户信息
Return: response -- 响应结果
"""
@router.get(
    "/api/system/user/info",
    tags=["后台用户管理"],
    summary="查询用户基本信息",
    response_model=models.RespJsonUserInfo,
)
async def get_user_info(
    id: int | None = None,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonUserInfo = Depends(
        response_code.RespSuccessJson.resp_200),
): 
    if id:
        # 构建查询语句
        statement = select(models.SystemUser).where(
            models.SystemUser.id == id,
            models.SystemUser.is_active == True,
            models.SystemUser.is_deleted == False,
        )
        # 如果id存在，查询指定用户信息
        content = session.exec(statement=statement).one_or_none()
        if not content:
            # 如果用户不存在，抛出异常
            raise exception.create_http_exception(detail="用户信息不存在")
    else:
        # 查询登录后台用户信息
        content = session.get(models.SystemUser, user.id)

    system_user_info = dict(content) if content else {}
    # 如果用户信息存在，添加角色信息
    if system_user_info:
        system_user_info["roles"] = [dict(role) for role in content.roles] if content.roles else []
        system_user_info["org_name"] = session.get(
            models.SystemOrg, system_user_info["org_id"]).name if system_user_info.get("org_id") else None
    else:
        # 保证org_name字段一定存在
        system_user_info["org_name"] = None
        system_user_info["roles"] = []

    # 构建响应数据
    response.data = system_user_info

    return response


"""查询当前用户拥有权限的用户

Keyword arguments:
skip -- 起始位置
limit -- 每页数量
username -- 用户名
name -- 昵称/姓名
org_id -- 所属组织机构
is_active -- 启用/停用
user -- 登录用户信息
Return: response -- 响应结果
"""


@router.get(
    "/api/system/user/",
    tags=["后台用户管理"],
    summary="查询当前用户拥有权限的用户",
    response_model=models.RespJsonUser,
)
async def get_user(
    skip: int = 0,
    limit: int = 20,
    username: str | None = None,
    name: str | None = None,
    org_id: int | None = None,
    is_active: int | None = None,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonUser = Depends(response_code.RespSuccessJson.resp_200),
):
    # 查询当前用户拥有权限的用户
    content = user_crud.get_user(
        skip, limit, username, name, org_id, is_active, user, session
    )
    
    # 构建响应数据
    response.data = {
        "total": content[1],
        "totalPages": content[1] // limit + 1 if content[1] % limit else content[1] // limit,
        "items": [dict(item) for item in content[0]] if content[0] else [],
    }

    return response


"""新增/注册用户

Keyword arguments:
user_create -- 新增用户信息
user -- 登录用户信息
Return: response -- 响应结果
"""


@router.post(
    "/api/system/user/",
    tags=["后台用户管理"],
    summary="新增/注册用户",
    response_model=models.RespJsonUser,
)
async def create_user(
    user_create: models.SystemUserCreate,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonUser = Depends(response_code.RespSuccessJson.resp_201),
):
    # 新增用户
    user_crud.create_user(user_create, user, session)

    return response


"""编辑用户

Keyword arguments:
id -- 用户id
user_update -- 编辑用户信息
user -- 登录用户信息
Return: response -- 响应结果
"""


@router.put(
    "/api/system/user/{id}",
    tags=["后台用户管理"],
    summary="编辑用户",
    response_model=models.RespJsonUser,
)
async def update_user(
    id: int,
    user_update: models.SystemUserUpdate,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonUser = Depends(response_code.RespSuccessJson.resp_202),
):

    user_crud.update_user(id, user_update, user, session)
    return response


"""删除用户（软删除）

Keyword arguments:
id -- 用户id
Return: response -- 响应结果
"""


@router.delete(
    "/api/system/user/",
    tags=["后台用户管理"],
    summary="删除用户",
    response_model=models.RespJsonUser,
)
async def delete_user(
    ids: list[int],
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonUser = Depends(response_code.RespSuccessJson.resp_204),
):
    for id in ids:
        # 删除用户
        user_crud.delete_user(id, user, session)
    return response


"""密码重置

Keyword arguments:
id -- 用户id
Return: response -- 响应结果
"""


@router.put(
    "/api/system/user/reset/{id}",
    tags=["后台用户管理"],
    summary="重置密码",
    response_model=models.RespJsonUser,
)
async def reset_password(
    id: int,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonUser = Depends(
        response_code.RespSuccessJson.resp_202_reset_password
    ),
):
    user_crud.reset_password(id, user, session)
    response.msg == "密码重置成功"

    return response


"""修改密码

Keyword arguments:
argument -- description
Return: return_description
"""


@router.put(
    "/api/system/user/modify/{id}",
    tags=["后台用户管理"],
    summary="修改密码",
    response_model=models.RespJsonUser,
)
async def modify_password(
    id: int,
    passwords: models.SystemUserModifyPassword,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonUser = Depends(
        response_code.RespSuccessJson.resp_202_modify_password
    ),
):
    user_crud.modify_password(id, passwords, user, session)
    return response
